package com.nf.dao;

import com.nf.entity.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Scope("prototype")
public class StudentDaoImpl implements StudentDao{

    public List<Student> getAllStudent() {
        List<Student> studentList = null;
        //第一步：加载hibernate核心配置文件
        //到src下面找到名为hibernate.cfg,xml
        //在hibernate里面封装对象
        Configuration cfg=new Configuration();
        cfg.configure();
        //第二步：创建sessionfactory对象
        //读取hibernate核心配置文件内容  创建sessionfactory
        //在过程中根据映射关系在数据库里把表创建
        SessionFactory sessionFactory = cfg.buildSessionFactory();
        Session session = sessionFactory.openSession();

        Query query1 = session.createQuery("from Student order by id desc");//查询所有记录

        /*Query query2 = session.createNamedQuery("selectStudentById");
        query.setParameter("myid",2);*/  //查询大于2的所有记录

        /*Query query3=session.createNamedQuery("myQuery",Student.class);//条件查询
        query.setParameter("myid",3);*/   //接受传过来的参数查询
        //条件查询
       /* Query query4 = session.createQuery("from Student where id=? and name=?");
        query4.setParameter(0,1);
        query4.setParameter(1,"习近平");*/
        studentList = query1.getResultList();

        for (Student student:studentList){
            System.out.println(student.getId()+":"+student.getName());
        }
        session.close();
        sessionFactory.close();

        System.out.println(studentList+"大小:"+studentList.size());

        return studentList;
    }
}
